package hip.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * @author Loanin
 * @date 2014年7月11日
 * @describe 时间处理工具类
 */
public class DateUtil {

    private static Calendar calendar;

    public static void setCompleteDate(Date completeDate) {
        calendar = Calendar.getInstance();
        calendar.setTime(completeDate);
    }

    // 某天是否完成
    public static boolean isComplete(Calendar comPareCalendar) {
        return comPareCalendar.after(calendar);
    }

    public static String dateFormatSort(Date date) {
        if (date == null)
            return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }

    public static String dateFormat(Date date) {
        if (date == null)
            return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    public static String dateFormat(Date date, String format) {
        if (date == null)
            return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    public static String dateFormatDT15(Date date) {
        if (date == null)
            return null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
        return dateFormat.format(date);
    }

    public static String dateFormatDT15(Object date) {
        if (date instanceof Date) {
            return dateFormatDT15((Date) date);
        }
        if (date != null)
            return date.toString();
        return "";
    }

    public static String dateFormatDT(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        return dateFormat.format(date);
    }

    public static Date parseStringToDate(String value) throws ParseException {
        if (StringUtils.isNotBlank(value)) {
            if (value.contains("-")) {
                if (value.length() < 11)
                    return DateUtils.parseDate(StringUtils.substringBefore(value, "."), "yyyy-MM-dd");
                return DateUtils.parseDate(StringUtils.substringBefore(value, "."), "yyyy-MM-dd HH:mm:ss");
            } else {
                if (value.length() == 8)
                    return DateUtils.parseDate(value, "yyyyMMdd");
                return DateUtils.parseDate(value, "yyyyMMddHHmmss");
            }

        }
        return null;
    }

    // 这个函数负责建 各种不规范的时间字符串转换为java的时间类型
    public synchronized static Date stringToDate(String value) {// 将
        if (StringUtils.isBlank(value)) {
            return null;
        }

        String df = "";
        if (value.length() == 15) {
            df = "yyyyMMdd'T'HHmmss";
        } else if (value.length() == 14) {
            df = "yyyyMMddHHmmss";
        } else if (value.length() == 8) {
            df = "yyyyMMdd";
        } else {
            boolean isHasT = false;
            // 时间字符串转为时间
            // String valueString = "2014-2-3 12:3:2";
            String[] di = null;
            if (value.contains("T")) {// 有T的用T截断
                di = value.split("T");
                isHasT = true;
            } else
                di = value.split(" ");

            if (di.length >= 1) {
                int c = di[0].split("-").length;
                if (c >= 1)
                    df += "yyyy";
                if (c >= 2)
                    df += "-MM";
                if (c >= 3)
                    df += "-dd";
            }
            if (di.length >= 2) {
                if (isHasT)
                    df += "'T'";
                int c = di[1].split(":").length;
                if (c >= 1)
                    df += "HH";
                if (c >= 2)
                    df += ":mm";
                if (c >= 3)
                    df += ":ss";
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat(df);
        try {
            return sdf.parse(value);
        } catch (ParseException e) {
            return null;
        }
    }

    @SuppressWarnings("static-access")
    public static Date addDateToYear(Date date, int year) {
        Date da = (Date) date.clone();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(da);
        calendar.add(calendar.YEAR, year);
        da = calendar.getTime();
        return da;
    }

    @SuppressWarnings("static-access")
    public static Date addDateToMonth(Date date, int month) {
        Date da = (Date) date.clone();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(da);
        calendar.add(calendar.MONTH, month);
        da = calendar.getTime();
        return da;
    }

    @SuppressWarnings("static-access")
    public static Date addDateToDay(Date date, int day) {
        Date da = (Date) date.clone();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(da);
        calendar.add(calendar.DATE, day);// 把日期往后增加一天.整数往后推,负数往前移动
        da = calendar.getTime(); // 这个时间就是日期往后推一天的结果
        return da;
    }

    @SuppressWarnings("static-access")
    public static Date addDateToHour(Date date, int hour) {
        Date da = (Date) date.clone();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(da);
        calendar.add(calendar.HOUR, hour);
        da = calendar.getTime();
        return da;
    }

    public static boolean compareEffectiveTime(Date headItemET, Date indexFlagET) {
        Calendar headItemCalendar = Calendar.getInstance();
        Calendar indexFlagCalendar = Calendar.getInstance();
        headItemCalendar.setTime(headItemET);
        indexFlagCalendar.setTime(indexFlagET);
        return headItemCalendar.before(indexFlagCalendar);
    }

    /**
     * 比较时间
     * 字符串格式
     * startTime<endTime  返回 true
     */
    public static boolean compareEffectiveTime(String startTime, String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calstartTime = Calendar.getInstance();
        Calendar calendTime = Calendar.getInstance();
        try {
            calstartTime.setTime(df.parse(startTime));
            calendTime.setTime(df.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calstartTime.before(calendTime);
    }

    /**
     * 传入日期 大于 当前时间 为true
     *
     * @param time
     * @return
     */
    public static boolean compareEffectiveTime(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calTime = Calendar.getInstance();
        Calendar calCurrent = Calendar.getInstance();
        Date d = new Date();
        try {
            calTime.setTime(df.parse(time));
            calCurrent.setTime(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calTime.after(calCurrent);
    }

    public static String formatDateToString(Object obj, String pattern) throws Exception {
        if ("yyyyMMdd'T'hhmmss".equals(pattern)) { // 由于开始写服务的时候，用的是yyyyMMdd'T'hhmmss 12小时制的，后来由于不想每个服务都改，所以直接在这里面替换
            pattern = "yyyyMMdd'T'HHmmss";
        }
        if (obj instanceof Date) {
            return DateFormatUtils.format((Date) obj, pattern);
        }
        return null;
    }

    public static String formatDateToString(Object obj) throws ParseException {
        if (obj != null && !"".equals(obj.toString())) {
            if (obj instanceof Date)
                return DateFormatUtils.format((Date) obj, "yyyyMMddHHmmss");
            else if (obj instanceof String)
                return DateFormatUtils.format(parseStringToDate(obj.toString()), "yyyyMMddHHmmss");
        }
        return null;
    }

    /**
     * 得到下一天  / 下一小时 / 下一分钟
     */
    public static String getNextDay(String dateTime, int dayCount,
                                    String logTimeUnit) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(df.parse(dateTime));
        } catch (ParseException e) {
            throw new RuntimeException("转化时间出错，传入的时间为" + dateTime, e);
        }
        if (logTimeUnit.equals("day")) {
            cal.add(Calendar.DATE, dayCount);
        } else if (logTimeUnit.equals("hour")) {
            cal.add(Calendar.HOUR, dayCount);
        } else {
            cal.add(Calendar.MINUTE, dayCount);
        }
        return df.format(cal.getTime());
    }

    /**
     * 得到当前时间
     */
    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        return df.format(d);
    }

    /**
     * 计算间隔天数 Date格式
     */
    public static int daysBetween(Date smdate, Date bdate)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算间隔天数 字符串 格式
     */
    public static int daysBetween(String smdate, String bdate)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 方法说明 ：计算smdate和bdate相减的小时数减去日期
     * 创立日期 ：2016年9月26日-下午9:09:22
     * 创建人   ：Jerry
     * 修改记录 ：修改人  修改原因  修改时间
     */

    public static int hoursBetween(String smdate, String bdate)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 60 * 60);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 方法说明 ：计算smdate和bdate相减的小时数减去日期和小时
     * 创立日期 ：2016年9月26日-下午9:09:22
     * 创建人   ：Jerry
     * 修改记录 ：修改人  修改原因  修改时间
     */

    public static int minutesBetween(String smdate, String bdate)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 60);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 方法说明 ：计算smdate和bdate相减的小时数减去日期和小时,分
     * 创立日期 ：2016年9月26日-下午9:09:22
     * 创建人   ：Jerry
     * 修改记录 ：修改人  修改原因  修改时间
     */

    public static int secondBetween(String smdate, String bdate)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000);
        return Integer.parseInt(String.valueOf(between_days));
    }

    public static synchronized boolean isBefore(String start, String end) {
        start = start.substring(0, 10);
        end = end.substring(0, 10);
        String starts[] = start.split("-");
        String ends[] = end.split("-");
        if (starts.length != 3 || ends.length != 3) {
            return false;
        }
        if (Integer.valueOf(starts[0]) > Integer.valueOf(ends[0])) {
            return false;
        }
        if (Integer.valueOf(starts[1]) > Integer.valueOf(ends[1])) {
            return false;
        }
        if (Integer.valueOf(starts[2]) > Integer.valueOf(ends[2])) {
            return false;
        }
        return true;
    }

}
